package io.renren.modules.mvs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.renren.common.annotation.SysLog;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.mvs.dto.OwnerLoginForm;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysRoleEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static io.renren.common.utils.Constant.VEHICLE_OWNER;

@RestController
@RequestMapping("/mvs/owner")
public class VehicleOwnerController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody OwnerLoginForm form) throws IOException {
        //用户信息
        SysUserEntity user = sysUserService.getOne(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getId, form.getId()));

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return R.error("输入信息错误");
        }

        List<SysRoleEntity> roles = sysRoleService.queryRoleListByUserId(user.getUserId());
        // 该登录接口只有机动车车主才可以使用
        if (!(roles.size() == 1 && roles.get(0).getRoleName().equals(VEHICLE_OWNER))) {
            return R.error("只有机动车车主才能登录");
        }

        //账号锁定
        if (user.getStatus() == 0) {
            return R.error("账号已被锁定");
        }

        //生成token，并保存到数据库
        return sysUserTokenService.createToken(user.getUserId());
    }

    /**
     * 获取登录的用户信息
     */
    @GetMapping("/info")
    public R info() {
        return R.ok().put("user", getUser());
    }

    /**
     * 根据机动车车主列表
     */
    @GetMapping("/list")
    @RequiresPermissions("mvs:owner:list")
    public R list() {
        List<SysUserEntity> userList = sysUserService.getListByRole(VEHICLE_OWNER);
        return R.ok().put("userList", userList);
    }

    /**
     * 获取机动车车主列表，并且支持分页
     */
    @GetMapping("/list/page")
    @RequiresPermissions("mvs:owner:list")
    public R page(@RequestParam Map<String, Object> params) {
        PageUtils page = sysUserService.getPageByRole(VEHICLE_OWNER, params);
        return R.ok().put("page", page);
    }

    /**
     * 检查当前用户的密码是否正确
     */
    @PostMapping("/check/pwd")
    @RequiresPermissions("mvs:owner:info")
    public R checkPassword(@RequestBody Map<String, String> data) {
        SysUserEntity user = sysUserService.getById(getUserId());
        String pwd = new Sha256Hash(data.get("password"), getUser().getSalt()).toHex();
        if (user.getPassword().equals(pwd)) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    @RequiresPermissions("mvs:owner:info")
    public R info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.getById(userId);
        return R.ok().put("user", user);
    }

    /**
     * 保存车主
     */
    @SysLog("保存车主")
    @PostMapping("/save")
    @RequiresPermissions("mvs:owner:save")
    public R save(@RequestBody SysUserEntity user) {
        user.setCreateUserId(getUserId());
        sysUserService.saveVehicleOwner(user);
        return R.ok();
    }

    /**
     * 修改车主
     */
    @SysLog("修改车主")
    @PostMapping("/update")
    @RequiresPermissions("mvs:owner:update")
    public R update(@RequestBody SysUserEntity user) {
        user.setCreateUserId(getUserId());
        sysUserService.updateVehicleOwner(user);
        return R.ok();
    }
}
